// 简化版本的MotionTracker类
class MotionTracker {
    constructor() {
        // 获取DOM元素
        this.canvas = document.getElementById('trackCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.startBtn = document.getElementById('startBtn');
        this.resetBtn = document.getElementById('resetBtn');
        this.statusText = document.getElementById('statusText');
        this.accelerationEl = document.getElementById('acceleration');
        this.rotationEl = document.getElementById('rotation');
        this.positionEl = document.getElementById('position');

        // 初始化变量
        this.isTracking = false;
        this.startX = 0;
        this.startY = 0;
        this.currentX = 0;
        this.currentY = 0;
        this.lastTimestamp = 0;
        
        // 用于滤波的数据
        this.accelData = { x: 0, y: 0, z: 0 };
        this.rotationData = { alpha: 0, beta: 0, gamma: 0 };
        this.velocity = { x: 0, y: 0 };
        
        // 设备方向
        this.deviceOrientation = { alpha: 0, beta: 0, gamma: 0 };
        
        // 步行检测 - 简化版本
        this.stepDetector = {
            accelerationSamples: [],
            lastPeakTime: 0,
            stepCount: 0,
            isWalking: false,
            peakThreshold: 0.9,      // 中等阈值
            minTimeBetweenSteps: 250 // 步伐间最小时间间隔
        };
        
        // 方向相关
        this.initialHeading = null;
        this.lastHeading = null;
        
        // 滤波系数
        this.filterCoef = 0.7; // 中等滤波
        
        // 绑定事件处理器
        this.startBtn.addEventListener('click', this.toggleTracking.bind(this));
        this.resetBtn.addEventListener('click', this.resetTracking.bind(this));
        
        // 初始化画布
        this.resizeCanvas();
        window.addEventListener('resize', this.resizeCanvas.bind(this));
        
        // 初始渲染
        this.render();
        
        // 添加调试信息区域
        this.createDebugInfo();
    }
    
    createDebugInfo() {
        // 创建调试信息区域
        const infoDiv = document.createElement('div');
        infoDiv.className = 'debug-info';
        infoDiv.innerHTML = `
            <div>步数: <span id="stepCount">0</span></div>
            <div>行走状态: <span id="walkingStatus">静止</span></div>
            <div>加速度峰值: <span id="accelPeak">0</span></div>
        `;
        document.querySelector('.info').appendChild(infoDiv);
        
        this.debugElements = {
            stepCount: document.getElementById('stepCount'),
            walkingStatus: document.getElementById('walkingStatus'),
            accelPeak: document.getElementById('accelPeak')
        };
    }
    
    resizeCanvas() {
        const container = this.canvas.parentElement;
        this.canvas.width = container.clientWidth;
        this.canvas.height = container.clientHeight;
        this.render();
    }
    
    toggleTracking() {
        if (!this.isTracking) {
            // 检查设备是否支持所需传感器
            if (typeof DeviceMotionEvent === 'undefined' || typeof DeviceOrientationEvent === 'undefined') {
                this.statusText.textContent = '错误: 您的设备不支持运动传感器';
                return;
            }
            
            // 在较新的iOS上，需要请求权限
            if (typeof DeviceMotionEvent.requestPermission === 'function') {
                DeviceMotionEvent.requestPermission()
                    .then(permissionState => {
                        if (permissionState === 'granted') {
                            this.startTracking();
                        } else {
                            this.statusText.textContent = '错误: 未授予传感器权限';
                        }
                    })
                    .catch(console.error);
            } else {
                this.startTracking();
            }
        } else {
            this.stopTracking();
        }
    }
    
    startTracking() {
        // 设置起始点为画布中心
        this.startX = this.canvas.width / 2;
        this.startY = this.canvas.height / 2;
        this.currentX = this.startX;
        this.currentY = this.startY;
        
        // 清空画布并绘制起始点
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.drawPoint(this.startX, this.startY, 'green', 5);
        
        // 添加事件监听器
        window.addEventListener('devicemotion', this.handleMotion.bind(this));
        window.addEventListener('deviceorientation', this.handleOrientation.bind(this));
        
        this.isTracking = true;
        this.startBtn.textContent = '停止跟踪';
        this.statusText.textContent = '正在跟踪';
        this.lastTimestamp = performance.now();
        
        // 重置初始方向
        this.initialHeading = null;
        this.lastHeading = null;
        
        // 开始动画循环
        requestAnimationFrame(this.updatePosition.bind(this));
    }
    
    stopTracking() {
        window.removeEventListener('devicemotion', this.handleMotion.bind(this));
        window.removeEventListener('deviceorientation', this.handleOrientation.bind(this));
        
        this.isTracking = false;
        this.startBtn.textContent = '开始跟踪';
        this.statusText.textContent = '已停止';
    }
    
    resetTracking() {
        if (this.isTracking) {
            this.stopTracking();
        }
        
        // 重置数据
        this.accelData = { x: 0, y: 0, z: 0 };
        this.rotationData = { alpha: 0, beta: 0, gamma: 0 };
        this.velocity = { x: 0, y: 0 };
        this.deviceOrientation = { alpha: 0, beta: 0, gamma: 0 };
        this.currentX = 0;
        this.currentY = 0;
        
        // 重置步行检测器
        this.stepDetector = {
            accelerationSamples: [],
            lastPeakTime: 0,
            stepCount: 0,
            isWalking: false,
            peakThreshold: 0.9,
            minTimeBetweenSteps: 250
        };
        
        // 重置方向
        this.initialHeading = null;
        this.lastHeading = null;
        
        // 更新调试信息
        if (this.debugElements) {
            this.debugElements.stepCount.textContent = '0';
            this.debugElements.walkingStatus.textContent = '静止';
            this.debugElements.accelPeak.textContent = '0';
        }
        
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.statusText.textContent = '准备就绪';
        
        // 更新显示数据
        this.updateDisplayData();
    }
    
    handleMotion(event) {
        // 应用低通滤波
        const accel = event.accelerationIncludingGravity;
        if (!accel) return;
        
        // 简单滤波
        this.accelData.x = this.accelData.x * this.filterCoef + accel.x * (1 - this.filterCoef);
        this.accelData.y = this.accelData.y * this.filterCoef + accel.y * (1 - this.filterCoef);
        this.accelData.z = this.accelData.z * this.filterCoef + accel.z * (1 - this.filterCoef);
        
        // 更新显示数据
        this.accelerationEl.textContent = `X: ${this.accelData.x.toFixed(2)}, Y: ${this.accelData.y.toFixed(2)}, Z: ${this.accelData.z.toFixed(2)}`;
        
        // 检测步行
        this.detectSteps();
    }
    
    handleOrientation(event) {
        if (!event.alpha && !event.beta && !event.gamma) return;
        
        // 应用低通滤波
        this.rotationData.alpha = this.rotationData.alpha * this.filterCoef + event.alpha * (1 - this.filterCoef);
        this.rotationData.beta = this.rotationData.beta * this.filterCoef + event.beta * (1 - this.filterCoef);
        this.rotationData.gamma = this.rotationData.gamma * this.filterCoef + event.gamma * (1 - this.filterCoef);
        
        // 计算罗盘方向 (compassHeading)
        let compassHeading = this.rotationData.alpha;
        
        // 如果设备不是平放的，需要根据beta和gamma角度调整alpha值
        if (this.rotationData.beta > 0) {
            compassHeading = 360 - this.rotationData.alpha;
        }
        
        // 转为弧度
        const alpha = (compassHeading * Math.PI) / 180;
        
        // 计算设备朝向
        this.deviceOrientation = {
            alpha: alpha,
            beta: (this.rotationData.beta * Math.PI) / 180,
            gamma: (this.rotationData.gamma * Math.PI) / 180,
            compassHeading: (compassHeading * Math.PI) / 180
        };
        
        // 更新显示数据
        this.rotationEl.textContent = `α: ${this.rotationData.alpha.toFixed(2)}, β: ${this.rotationData.beta.toFixed(2)}, γ: ${this.rotationData.gamma.toFixed(2)}`;
    }
    
    detectSteps() {
        // 计算加速度总量
        const accelMagnitude = Math.sqrt(
            Math.pow(this.accelData.x, 2) + 
            Math.pow(this.accelData.y, 2) + 
            Math.pow(this.accelData.z - 9.81, 2) // 减去重力
        );
        
        // 保存加速度样本
        this.stepDetector.accelerationSamples.push({
            magnitude: accelMagnitude,
            timestamp: performance.now()
        });
        
        // 限制样本数量
        if (this.stepDetector.accelerationSamples.length > 20) {
            this.stepDetector.accelerationSamples.shift();
        }
        
        // 更新加速度峰值显示
        if (this.debugElements && this.debugElements.accelPeak) {
            this.debugElements.accelPeak.textContent = accelMagnitude.toFixed(2);
        }
        
        // 检测步行 - 简化版本
        const now = performance.now();
        const timeSinceLastPeak = now - this.stepDetector.lastPeakTime;
        
        // 计算加速度变化
        let isSignificantMotion = false;
        if (this.stepDetector.accelerationSamples.length >= 5) {
            const recentSamples = this.stepDetector.accelerationSamples.slice(-5);
            const maxMag = Math.max(...recentSamples.map(s => s.magnitude));
            const minMag = Math.min(...recentSamples.map(s => s.magnitude));
            const variation = maxMag - minMag;
            
            // 简单判断是否有显著运动
            isSignificantMotion = variation > 0.3;
        }
        
        // 检测步伐
        if (accelMagnitude > this.stepDetector.peakThreshold && 
            timeSinceLastPeak > this.stepDetector.minTimeBetweenSteps && 
            isSignificantMotion) {
            
            // 检测到一步
            this.stepDetector.lastPeakTime = now;
            this.stepDetector.stepCount++;
            this.stepDetector.isWalking = true;
            
            // 更新调试信息
            if (this.debugElements) {
                this.debugElements.stepCount.textContent = this.stepDetector.stepCount;
                this.debugElements.walkingStatus.textContent = '行走中';
            }
            
            // 根据步行和方向更新位置
            this.updatePositionFromStep();
            
            // 重置行走状态的计时器
            clearTimeout(this.stepDetector.walkingTimeout);
            this.stepDetector.walkingTimeout = setTimeout(() => {
                this.stepDetector.isWalking = false;
                if (this.debugElements) {
                    this.debugElements.walkingStatus.textContent = '静止';
                }
            }, 2000); // 2秒内没有新步伐则认为停止行走
        }
    }
    
    updatePositionFromStep() {
        if (!this.isTracking) return;
        
        // 获取当前方向
        const currentHeading = this.deviceOrientation.compassHeading || this.deviceOrientation.alpha;
        
        // 如果初始方向尚未设置，则设置它
        if (this.initialHeading === null) {
            this.initialHeading = currentHeading;
            this.lastHeading = 0; // 相对方向初始为0
            console.log("初始方向设置为:", this.initialHeading * 180 / Math.PI, "度");
        }
        
        // 计算相对于初始方向的角度差
        let relativeHeading = currentHeading - this.initialHeading;
        
        // 规范化角度到 [-π, π]
        while (relativeHeading > Math.PI) relativeHeading -= 2 * Math.PI;
        while (relativeHeading < -Math.PI) relativeHeading += 2 * Math.PI;
        
        // 简单平滑处理
        let finalHeading;
        if (this.lastHeading !== null) {
            // 使用简单的平滑因子
            const smoothFactor = 0.3; // 30%新值，70%旧值
            finalHeading = this.lastHeading * (1 - smoothFactor) + relativeHeading * smoothFactor;
        } else {
            finalHeading = relativeHeading;
        }
        
        // 更新上次使用的方向
        this.lastHeading = finalHeading;
        
        // 计算方向向量 - 使用v21.html的方式
        const directionX = Math.sin(finalHeading);  // 向右为正
        const directionY = -Math.cos(finalHeading); // 向上为负
        
        // 上一个位置
        const prevX = this.currentX;
        const prevY = this.currentY;
        
        // 使用固定步长
        const stepScale = 18; // 固定步长
        
        // 根据步长和方向更新位置
        this.currentX += directionX * stepScale;
        this.currentY += directionY * stepScale;
        
        // 确保轨迹不超出画布
        this.currentX = Math.max(0, Math.min(this.canvas.width, this.currentX));
        this.currentY = Math.max(0, Math.min(this.canvas.height, this.currentY));
        
        // 画线
        this.drawLine(prevX, prevY, this.currentX, this.currentY, 'blue', 2);
        
        // 更新位置显示
        this.positionEl.textContent = `X: ${this.currentX.toFixed(2)}, Y: ${this.currentY.toFixed(2)}`;
        
        // 添加调试信息
        if (this.debugElements) {
            // 如果没有方向调试信息，添加一个
            if (!this.debugElements.direction) {
                const directionDiv = document.createElement('div');
                directionDiv.innerHTML = `方向: <span id="direction">0°</span>`;
                document.querySelector('.debug-info').appendChild(directionDiv);
                this.debugElements.direction = document.getElementById('direction');
            }
            
            // 更新方向显示（转换为度数）
            const degrees = (finalHeading * 180 / Math.PI) % 360;
            this.debugElements.direction.textContent = `${degrees.toFixed(1)}° (初始: ${(this.initialHeading * 180 / Math.PI).toFixed(1)}°)`;
        }
    }
    
    updatePosition(timestamp) {
        if (!this.isTracking) return;
        
        // 计算时间增量（秒）
        const deltaTime = (timestamp - this.lastTimestamp) / 1000;
        this.lastTimestamp = timestamp;
        
        // 继续动画循环
        requestAnimationFrame(this.updatePosition.bind(this));
    }
    
    drawPoint(x, y, color, size) {
        this.ctx.fillStyle = color;
        this.ctx.beginPath();
        this.ctx.arc(x, y, size, 0, Math.PI * 2);
        this.ctx.fill();
    }
    
    drawLine(x1, y1, x2, y2, color, width) {
        this.ctx.strokeStyle = color;
        this.ctx.lineWidth = width;
        this.ctx.beginPath();
        this.ctx.moveTo(x1, y1);
        this.ctx.lineTo(x2, y2);
        this.ctx.stroke();
    }
    
    render() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 如果正在跟踪，绘制起始点
        if (this.isTracking) {
            this.drawPoint(this.startX, this.startY, 'green', 5);
        }
    }
    
    updateDisplayData() {
        this.accelerationEl.textContent = `X: 0, Y: 0, Z: 0`;
        this.rotationEl.textContent = `α: 0, β: 0, γ: 0`;
        this.positionEl.textContent = `X: 0, Y: 0`;
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new MotionTracker();
}); 